package br.com.emmis.tercons.services;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import br.com.emmis.tercons.MainActivity;
import br.com.emmis.tercons.R;
import br.com.emmis.tercons.constants.Constants;
import br.com.emmis.tercons.model.Config;
import br.com.emmis.tercons.model.Intention;
import br.com.emmis.tercons.util.IntentionXMLUtil;
import br.com.emmis.tercons.util.SettingsXMLUtil;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class CheckIntentionsService extends IntentService {
    private static final String DEBUG_TAG = "CheckIntentionsService";

    private static final String DOWNLOAD_CREATE_INTENTION_XML = "br.com.emmis.tercons.services.action.DOWNLOAD_CREATE_INTENTION_XML";

    private int mLastIntentionId = -1;

    public CheckIntentionsService() {
        super("CheckIntentions");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionDownloadCreateDonationXML(Context context) {

        Log.d(DEBUG_TAG, "startActionDownloadCreateDonationXML - start");

        Intent intent = new Intent(context, CheckIntentionsService.class);
        intent.setAction(DOWNLOAD_CREATE_INTENTION_XML);
        context.startService(intent);

    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (DOWNLOAD_CREATE_INTENTION_XML.equals(action)) {
                try {
                    downloadAndCreateIntentionXML();
                } catch (IOException e) {
                    Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - IOException");
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - ParserConfigurationException");
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void downloadAndCreateIntentionXML() throws IOException, ParserConfigurationException {

        Log.d(DEBUG_TAG, "downloadAndCreateIntentionXML - start");
        Config config = Config.getInstance(getApplicationContext());

        IntentionXMLUtil intentionXMLUtil = null;

        Intention last_intention = null;

        try {
            byte[] buffer = new byte[90000];


            FileInputStream fis = openFileInput(Constants.INTENTIONS_XML_FILE);
            fis.read(buffer);
            fis.close();

            intentionXMLUtil = new IntentionXMLUtil(buffer);
            last_intention = intentionXMLUtil.getLastIntention();
        } catch (FileNotFoundException ex) {
            Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - No intention File");
        } catch (SAXException e) {
            Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - XML file corrupted");
            deleteFile(Constants.INTENTIONS_XML_FILE);
        }

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(config.getmIntentionURL() + Constants.GET_INTENTIONS_URL);

        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_IDIOMA, config.getmLocation()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String line = EntityUtils.toString(httpEntity);

        Intention intention = null;
        if(line.contains(Constants.XML_NODE_INTENCOES)) {
            line = line.substring(line.indexOf(Constants.XML_NODE_INTENCOES));

            try {
                intentionXMLUtil = new IntentionXMLUtil(line.getBytes("ISO-8859-1"));
                intention = intentionXMLUtil.getLastIntention();

                SettingsXMLUtil settingsUtil = new SettingsXMLUtil(line.getBytes("ISO-8859-1"));
                String url = settingsUtil.getURL();
                if(url != null) {
                    config.setmIntentionURL(url);
                }
            } catch (SAXException e) {
                Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - XML received corrupted.");
            }

            FileOutputStream outputStream = openFileOutput(Constants.INTENTIONS_XML_FILE, Context.MODE_PRIVATE);
            outputStream.write(line.getBytes("ISO-8859-1"));
            outputStream.close();

            if (last_intention != null && intention != null && !last_intention.equals(intention) && config.ismNotifyIntentions()) {
                Log.d(DEBUG_TAG, "downloadAndCreateIntentionXML - Notify new Intention");
                mLastIntentionId = intention.getmId();

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_stat_terco)
                                .setContentTitle(getString(R.string.intention_notification_title))
                                .setContentText(getString(R.string.intention_notification_name)+ " " + intention.getmName());

                Intent resultIntent = new Intent(this, MainActivity.class);
                resultIntent.setAction(Constants.ACTION_INTENTION_NOTIFICATION);
                resultIntent.putExtra(Constants.EXTRA_INTENTION_ID, intention.getmId());
                resultIntent.putExtra(Constants.EXTRA_INTENTION_NAME, intention.getmName());
                resultIntent.putExtra(Constants.EXTRA_INTENTION_PRAY, intention.getmPrece());
                resultIntent.putExtra(Constants.EXTRA_INTENTION_AMEM, intention.getmAmem());

                // The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
                stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(resultIntent);

                // Because clicking the notification opens a new ("special") activity, there's
                // no need to create an artificial back stack.
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                0,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                mBuilder.setContentIntent(resultPendingIntent);
                mBuilder.setAutoCancel(true);

                // Sets an ID for the notification
                int mNotificationId = 001;
                // Gets an instance of the NotificationManager service
                NotificationManager mNotifyMgr =
                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                // Builds the notification and issues it.
                mNotifyMgr.notify(mNotificationId, mBuilder.build());
            }
        } else {
            Log.e(DEBUG_TAG, "downloadAndCreateIntentionXML - Deleting XML file with wrong URL");
            deleteFile(Constants.INTENTIONS_XML_FILE);
            config.setmIntentionURL(Constants.INTENTIONS_URL);
        }
    }
}
